﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Base class for all controls that rely on a built-in HTML field tag (INPUT, SELECT and TEXTAREA).
	/// </summary>
	[ParseChildren(true)]
	[PersistChildren(false)]
	public abstract class BaseFieldControl<T> : BaseValueControl<T>, ISimpleControl
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public BaseFieldControl()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#endregion
		#endregion
		#region INTERNAL
		#region PROPS
		/// <summary>
		/// Gets or sets the <see cref="BaseValueControl{T}.Value"/>.
		/// </summary>
		protected internal override string SerializedValue
		{
			get
			{
				if (Value == null) return "";
				return Value.ToString();
			}
			set
			{
				try
				{
					Value = (T)Convert.ChangeType(value, typeof(T));
				}
				catch
				{
					throw new ArgumentException();
				}
			}
		}
		#endregion
		#region METHODS
		#region INIT
		/// <summary>
		/// Registers SimpleControl.js.
		/// </summary>
		protected internal override void RegisterIncludes(IncludeCollection includes)
		{
			base.RegisterIncludes(includes);

			SimpleControlCommon.RegisterIncludes(this, includes);
		}
		#endregion
		#region RENDER
		/// <summary>
		/// Calls <see cref="AddOnChangeAttributes"/> to add onchange attributes.
		/// </summary>
		/// <param name="writer"></param>
		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			AddOnChangeAttributes(writer);

			base.AddAttributesToRender(writer);
		}
		/// <summary>
		/// Adds onchange attribute (if any event handling attached).
		/// </summary>
		/// <param name="writer"></param>
		protected virtual void AddOnChangeAttributes(HtmlTextWriter writer)
		{
			string onchange = TControl.GetEventScript(ValueChanged.GetEventScript(null), Attributes["onchange"]);
			if (!string.IsNullOrEmpty(onchange))
				writer.AddAttribute(HtmlTextWriterAttribute.Onchange, onchange);
		}
		#endregion
		#endregion
		#endregion
	}
}